var utils = require("./utils");

if (!requestScreenCapture()) {
  toastLog("请求截图权限失败");
  exit();
}

function toArray(arrLike) {
  var array = [];
  for (var index = 0; index < arrLike.length; index++) {
    array.push(arrLike[index]);
  }
  return array;
}

function getCaptureImg() {
  var startTime = Date.now();
  console.log("getCaptureImg: 开始截图")
  var captureImg = captureScreen();
  if (!captureImg) {
    toastLog("截图失败");
  }
  var endTime = Date.now();
  console.log("getCaptureImg: 截图耗费-" + (endTime - startTime) / 1000 + "-s");
  return captureImg;
}

function getCaptureImgOcrResult() {
  var captureImg = getCaptureImg();
  var captureImgOrcResults = toArray(paddle.ocr(captureImg));
  captureImg.recycle();
  return captureImgOrcResults;
}

var OCR_UTIL_CONST_CHAR_MATCH_MAP = {
  搜: ["嫂", "樓", "接", "楼"],
  赚: ["廉", "嫌", "賺", "兼"],
  看: ["着", "春"],
  文: ["女"],
  章: ["拿"],
  钱: ["线"],
  觉: ["党"],
  户: ["戶"],
  索: ["素"],
  开: ["升", "研"],
  金: ["全"],
  积: ["枳"],
  币: ["市"],
  现: ["現"],
  领: ["領", "颌"],
  读: ["渎"],
  额: ["額"],
  取: ["驭"],
  视: ["规", "初"],
  享: ["亨"],
  兑: ["兌"],
  提: ["堤"],
  体: ["休"],
  才: ["オ"],
  街: ["衔"],
  城: ["械"],
  间: ["闻"],
  来: ["來"],
  十: ["+"],
};

var ocrPaddle = {
  getRegExp(content) {
    var regExpStr = content
      .split("")
      .map(function (item) {
        var match = OCR_UTIL_CONST_CHAR_MATCH_MAP[item];
        var piece = match
          ? "[" + match.concat(item).join("") + "]+"
          : "[" + item + "]+";
        return piece + `\\s*`;
      })
      .join("");
    return {
      text: content,
      regExp: new RegExp(regExpStr, "gi"),
    };
  },
  toArray: toArray,
  captureAndLogText() {
    var captureImgOrcResults = getCaptureImgOcrResult();
    console.log(
      "captureAndLogText:",
      captureImgOrcResults.map((item) => item.text).join("\n")
    );
  },
  captureExistAll(content, logInfo) {
    var logger = utils.createLogger("ocrPaddle captureExistAll: ");
    logger("");
    if (!Array.isArray(content)) {
      content = [content];
    }
    var contentConfigs = content.map((item) => {
      return {
        text: content,
        regExp: this.getRegExp(item).regExp,
        find: null,
      };
    });
    if (logInfo) {
      logger(
        "正则表达式是-" +
          contentConfigs.map((item) => item.regExp.toString()).join(" || ") +
          "-"
      );
    }
    var captureImgOrcResults = getCaptureImgOcrResult();
    for (var index = 0; index < captureImgOrcResults.length; index++) {
      var item = captureImgOrcResults[index];
      for (var j = 0; j < contentConfigs.length; j++) {
        var contentConfig = contentConfigs[j];
        if (!contentConfig.find && contentConfig.regExp.test(item.text)) {
          contentConfig.find = item;
          break;
        }
      }
      if (contentConfigs.every((item) => item.find)) {
        break;
      }
    }
    if (contentConfigs.some((item) => !item.find)) {
      if (logInfo) {
        var noFinds = contentConfigs
          .filter((item) => !item.find)
          .map((item) => item.text)
          .join(" || ");
        logger("没找到-" + noFinds + "-");
      }
      return false;
    }
    return true;
  },
  captureExistOne(content, logInfo) {
    if (!Array.isArray(content)) {
      content = [content];
    }
    var configs = content.map((item) => {
      return this.getRegExp(item);
    });
    if (logInfo) {
      console.log(
        "ocrPaddle captureExistOne: " +
          "正则表达式是：-" +
          configs.map((item) => item.regExp).join(" || ") +
          "-"
      );
    }
    return this.captureExistMatchOne(configs, logInfo);
  },
  captureExistMatchOne(regExpConfigs, logInfo) {
    var captureImgOrcResults = getCaptureImgOcrResult();
    for (var index = 0; index < captureImgOrcResults.length; index++) {
      var item = captureImgOrcResults[index];
      var find = regExpConfigs.find((regExpConfig) => {
        return regExpConfig.regExp.test(item.text);
      });
      if (find) {
        console.log(
          "captureExistMatchOne: 找到-" + item.text + "|" + find.text + "-"
        );
        return item;
      }
    }
    console.log(
      "ocrPaddle captureExistMatchOne: 没找到: " +
        regExpConfigs.map((item) => item.text).join(" || ")
    );
    if (logInfo) {
      this.logText(captureImgOrcResults);
    }
  },
  logText(captureImgOrcResults) {
    console.log(
      captureImgOrcResults.map(
        function (item) {
          return item.text;
        }.join("|")
      )
    );
  },
  findTextOne(content, logInfo, ifIsEnd, maxSwipeTimes, swipeInstace) {
    if (!Array.isArray(content)) {
      content = [content];
    }
    maxSwipeTimes = maxSwipeTimes || 10;
    logInfo = logInfo || false;
    swipeInstace = swipeInstace || (device.height / 10) * 1;
    var regExpConfigs = content.map((item) => {
      return this.getRegExp(item);
    });
    while (maxSwipeTimes > 0) {
      var result = this.captureExistMatch(regExpConfigs, logInfo);
      if (result) {
        return result;
      }
      utils.swipeX(
        ((device.width / 2) * utils.getRandom(90, 100)) / 100,
        ((device.height / 2) * utils.getRandom(90, 100)) / 100,
        ((device.width / 2) * utils.getRandom(90, 100)) / 100,
        ((device.height / 2 - swipeInstace) * utils.getRandom(90, 100)) / 100,
        utils.getRandom(500, 1000)
      );
      sleep(utils.getRandom(1, 1.5, 1000));
      maxSwipeTimes = maxSwipeTimes - 1;
      if (ifIsEnd && ifIsEnd()) {
        break;
      }
    }
  },
  findTextAll(content, logInfo, ifIsEnd, maxSwipeTimes, swipeInstace) {
    var logger = utils.createLogger("ocrPaddle findTextAll: ");
    if (!Array.isArray(content)) {
      content = [content];
    }
    var contentConfigs = content.map((item) => {
      return {
        text: item,
        regExp: this.getRegExp(item).regExp,
        result: null,
      };
    });
    if (logInfo) {
      logger(
        "正则表达式是： -" +
          contentConfigs.map((item) => item.regExp).join(" || ") +
          "-"
      );
    }
    maxSwipeTimes = maxSwipeTimes || 10;
    logInfo = logInfo || false;
    swipeInstace = swipeInstace || (device.height / 10) * 1;
    var ocrTextResults = [];
    while (maxSwipeTimes > 0) {
      var captureImgOrcResults = getCaptureImgOcrResult();
      for (var index = 0; index < captureImgOrcResults.length; index++) {
        var item = captureImgOrcResults[index];
        for (var j = 0; j < contentConfigs.length; j++) {
          var contentConfig = contentConfigs[j];
          var text = contentConfig.text;
          var regExp = contentConfig.regExp;
          var find = ocrTextResults.find(function (item) {
            return item.text == text;
          });
          if (!find && regExp.test(item.text)) {
            ocrTextResults.push({
              text,
              regExp,
              result: item,
            });
            logger("找到-" + item.text + "-");
            break;
          }
        }
        if (ocrTextResults.length == contentConfigs.length) {
          break;
        }
      }
      if (ocrTextResults.length > 0) {
        return ocrTextResults;
      }
      if (ocrTextResults.length == 0) {
        if (logInfo) {
        } else {
          logger(
            "当前页面没有找到-" +
              contentConfigs.map((item) => item.text).join(" || ")
          );
        }
      }
      utils.swipeX(
        ((device.width / 2) * utils.getRandom(90, 100)) / 100,
        ((device.height / 2) * utils.getRandom(90, 100)) / 100,
        ((device.width / 2) * utils.getRandom(90, 100)) / 100,
        ((device.height / 2 - swipeInstace) * utils.getRandom(90, 100)) / 100,
        utils.getRandom(500, 1000)
      );
      sleep(utils.getRandom(1, 1.5, 1000));
      maxSwipeTimes = maxSwipeTimes - 1;
      if (ifIsEnd && ifIsEnd()) {
        return ocrTextResults;
      }
    }
    return ocrTextResults;
  },
};

module.exports = ocrPaddle;
